package com.secneo.appshare.threads;

import java.util.ArrayList;

import android.content.Context;
import android.graphics.drawable.Drawable;
import android.os.Handler;
import android.os.Message;

import com.secneo.appshare.R;
import com.secneo.appshare.api.RemoteApi.AppInfo;
import com.secneo.appshare.api.impl.RemoteApiImpl;
import com.secneo.appshare.common.Constants;
import com.secneo.appshare.common.Util;

public class GetAppInfoThread extends Thread{
	private String package_name;
	private int number;
	private String uid;
	private boolean installed_not_addicted;
	private Context ctx;
	private Handler handler;
	private boolean running = true;
	private AppInfo retAppinfo;
	
	public GetAppInfoThread(Context ctx, Handler handler, String package_name, 
			int number, String uid, boolean installed_not_addicted) {
		this.package_name = package_name;
		this.number = number;
		this.uid = uid;
		this.installed_not_addicted = installed_not_addicted;
		this.ctx = ctx;
		this.handler = handler;
		retAppinfo = null;
	}
	
	public synchronized void stopRun(){
		running = false;
		this.interrupt();

	}
	
	public AppInfo getAppInfo() {
		return retAppinfo;
	}
	
	public void run() {
		try {
			RemoteApiImpl remoteApi = new RemoteApiImpl();
			retAppinfo = remoteApi.getApplicationInfo(ctx, package_name, 
					number, uid, installed_not_addicted);
			
			if(retAppinfo != null){
				if(retAppinfo.status.equals("ok")){
					handler.sendEmptyMessage(Constants.MODE_GET_ALL_APP_INFO) ;
					
					if(!running)	return ;
					
					if(retAppinfo.appDetails.icon_url != null){
						retAppinfo.appDetails.iconDrawable = 
							Util.getDrawableFromCache(ctx, 
									retAppinfo.appDetails.icon_url);
						if(retAppinfo.appDetails.iconDrawable == null){
							retAppinfo.appDetails.iconDrawable = 
								ctx.getResources().getDrawable(R.drawable.some_app) ;
						}
						handler.sendEmptyMessage(
								Constants.MSG_GET_APP_INFO_ICON_FINISH) ;
					}
					
					if(!running)	return ;
					
					int count = retAppinfo.appDetails.shortUrlList.size() ;
					retAppinfo.appDetails.shortDrawableList = 
								new ArrayList<Drawable>() ;
					for(int i = 0 ; i < count ; ++i){
						Drawable d = Util.getDrawableFromCache(ctx, 
								retAppinfo.appDetails.shortUrlList.get(i)) ;
						
						if(d != null){
							retAppinfo.appDetails.shortDrawableList.add(d) ;
							Message msg = new Message() ;
							msg.what = Constants.MSG_GET_APP_INFO_SHORT_FINISH ;
							msg.arg1 = i ;
							handler.sendMessage(msg) ;
						}
					}
				}
				else 
					handler.sendEmptyMessage(Constants.MSG_GET_APP_INFO_STATUS_ERROR) ;
			} else {
				handler.sendEmptyMessage(Constants.MSG_GET_APP_INFO_NETWORK_ERROR) ;
			}
			
		} catch (Exception e) {
			e.printStackTrace() ;
		}
	}	
}
